<?php
namespace app\api\service;

use app\api\model\Device;
use app\api\model\Order;
use think\db\BaseQuery;
use think\facade\Cache;
use think\facade\Log;

class VpayService {

  
    public function setHeartbeat(Device $device) {
        $device->heartbeat_time = date('Y-m-d H:i:s');
        $device->save();
    }

    public function queryDeviceStatus(Device $device){
        return $device->online_status;
    }

    public function checkDeviceParams($params){
        if(!isset($params['sign'])){
            throw new \Exception("缺少sign参数");
        }
        if(!isset($params['t'])){
            throw new \Exception("缺少t参数");
        }
    
        if(!isset($params['device_id'])){
            throw new \Exception("缺少device_id参数");
        }

        $time = $params['t'];
        $diff = time() - $time;
        if ($diff > 30){
            throw new \Exception("请求超时($diff)");
        }   
    }

    public function checkAppParams($params){
        if(!isset($params['sign'])){
            throw new \Exception("缺少sign参数");
        }
        if(!isset($params['t'])){
            throw new \Exception("缺少t参数");
        }

        if(!isset($params['appid'])){
            throw new \Exception("appid");
        }

        $time = $params['t'];
        $diff = time() - $time;
        if ($diff > 30){
            throw new \Exception("请求超时($diff)");
        }   
    }


    public function getDevice($deviceId){
        $device = Device::where('id', $deviceId)
        ->find();
        if(empty($device)){
            throw new \Exception("deviceId不存在");
        }

        return $device;
    }

    public function checkSign($params, $appsecret){
        $sign = $params['sign'];
        // 构建与 Android 端相同格式的 JSON 对象
        unset($params['sign']);
        ksort($params);
        $queryString = http_build_query($params);
        // 计算签名
        $newSign = md5($queryString .  $appsecret);
        if ($sign != $newSign) {
            Log::info($queryString.  $appsecret);
            Log::info($newSign ."\n".$sign);
            throw new \Exception('签名错误');   
        }
    }


    public function getIdleClient($type = null){
        return Device::whereOnline()
            ->order('heartbeat_time', 'asc')
            ->where(function(BaseQuery $query){
                if(empty($type)){
                    return ;
                }
                if($type == Order::PAY_TYPE_ALIPAY){
                    $query->whereNotNull('alipay');
                }
                else if($type == Order::PAY_TYPE_WECHAT){
                    $query->whereNotNull('wechat');
                }
            })
            ->limit(1)
            ->find();
    }
}